package com.baasp.gateway;

import com.baasp.gateway.config.GatewayConfig;
import com.baasp.gateway.config.IPRateLimiterConfig;
import com.baasp.gateway.filter.AuthFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@EnableConfigurationProperties({GatewayConfig.class})//指定配置类
@EnableFeignClients
public class BaaspGatewayApplication {

	@Resource
	private AuthFilter authFilter;

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}

	public static void main(String[] args) {
		SpringApplication.run(BaaspGatewayApplication.class, args);
	}


	/**
	 * 根据ip 限流
	 * @return
	 */
	@Bean
	public IPRateLimiterConfig hostAddrKeyResolver() {
		return new IPRateLimiterConfig();
	}

//	/**
//	 * 根据 用户 限流
//	 * @return
//	 */
//	@Bean
//	KeyResolver userKeyResolver() {
//		return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
//	}
//
//	/**
//	 * 根据 hostname 限流
//	 * @return
//	 */
//	@Bean
//	KeyResolver hostNameKeyResolver() {
//		return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
//	}

	@Bean
	public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
		return builder.routes()
				.route(r -> r.path("/api/**")
						.filters(f -> f.filter(authFilter))
						.uri("lb://baasp-backend")
				)
				.build();
	}

}
